import { injectPlusButtons } from "../components/PlusButtons";
import { DEBUG } from "@utils/constants";

export function setupPageObserver() {
  const observer = new MutationObserver((mutations) => {
    let significantChanges = false;
    mutations.forEach((mutation) => {
      if (mutation.addedNodes.length > 0) {
        mutation.addedNodes.forEach((node) => {
          if (node.nodeType === Node.ELEMENT_NODE) {
            const element = node as Element;
            const tagName = element.tagName?.toLowerCase();
            if (
              ["img", "video", "iframe", "form", "a"].includes(tagName) ||
              element.querySelectorAll("img, video, iframe, form, a").length > 0
            ) {
              significantChanges = true;
            }
          }
        });
      }
    });
    if (significantChanges && DEBUG) {
      console.log("🔄 Significant page changes detected");
    }
    injectPlusButtons(document);
  });

  observer.observe(document.body, {
    childList: true,
    subtree: true,
    attributes: false,
  });

  document.addEventListener("visibilitychange", () => {
    if (document.hidden) {
      console.log("😴 Page hidden");
    } else {
      console.log("👁️ Page visible");
    }
  });
}
